﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace PoemCrawler
{
    internal static class HtmlParser
    {
        public static string? GetPoem(string html)
        {
            string pattern = "<div class=\"main-content gushi-info\"><h1>(?<title>.*?)</h1><div class=\"author-simple-info\"><span>朝代：<a href=\".*?\">(?<dynasty>.*?)</a></span><span class=\"sep\">\\|</span><span>作者：<a href=\".*?\">(?<author>.*?)</a></span><span class=\"sep\">\\|</span></div><div class=\"shici-content check-more\">(?<htmlContent>[\\s\\S]*?)</div></div>";
            Regex r = new(pattern);
            Match m = r.Match(html);

            if (m.Success)
            {
                string title = m.Groups["title"].Value;
                string dynasty = m.Groups["dynasty"].Value;
                string author = m.Groups["author"].Value;
                string content = m.Groups["htmlContent"].Value.Replace("<p>", "\n").Replace("</p>", "\n");
                return $"{title}\n{dynasty} {author}\n{content}".Replace("\n\n", "\n") + "\n";
            }
            else
            {
                return null;
            }
        }
        public static WebPoems GetPoemUrls(string html)
        {
            WebPoems webPoems = new WebPoems();

            string pattern = "<li>[0-9]+?\\.《<a href=\"(?<url>.*?)\">(?<title>.*?)</a>》<a href=\".*?\">(?<dynasty>.*?)</a><span>·</span><a class=\"author\" href=\".*?\">(?<author>.*?)</a><span class=\"content\">(?<content>[\\s\\S]*?)</span></li>";
            Regex r = new(pattern);
            MatchCollection ms = r.Matches(html);

            foreach (Match m in ms)
            {
                string title = m.Groups["title"].Value;
                string url = m.Groups["url"].Value;
                string dynasty = m.Groups["dynasty"].Value;
                string author = m.Groups["author"].Value;
                string content = m.Groups["content"].Value;

                if(content.EndsWith("..."))
                    webPoems.urls.Add(url);
                else
                    webPoems.poems.Add($"{title}\n{dynasty} {author}\n{content}".Replace("\n\n", "\n") + "\n");
            }
            return webPoems;
        }

        public static int GetPoemPageCount(string html)
        {
            string pattern = "<li class='info'><span>.*?首,共(?<pageNumber>[0-9]+?)页</span></li>";
            Regex r = new(pattern, RegexOptions.IgnoreCase);
            Match m = r.Match(html);
            string[] res = m.Groups["pageNumber"].Captures.Cast<Capture>().Select(c => c.Value).ToArray();
            if (res.Length != 1)
                throw new Exception("GetPoemPageCount: html解析错误");
            return int.Parse(res[0]);
        }
    }
}
